package com.sgb.kjwl.viewmodel.pick;

import android.content.Intent;
import androidx.databinding.ObservableField;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;




import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;

import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.PickDeviceEntity2;
import com.sgb.kjwl.model.entity.PickLabourEntity;
import com.sgb.kjwl.model.entity.PickListUploadEntity;
import com.sgb.kjwl.model.entity.PickPackersEntity;
import com.sgb.link.utils.Preferences;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.ProjectBuyEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.model.entity.user.PickMaterialClassEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.repository.PickRepertory;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.kjwl.view.ui.fragment.pick.PickRequireListFragment3;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PickRequireListFragModel3 extends BaseViewModel {
    public ObservableField<PickListUploadEntity> listEntity1 = new ObservableField<>(new PickListUploadEntity());
    public ObservableField<PickListUploadEntity> listEntity2 = new ObservableField<>(new PickListUploadEntity());
    public ObservableField<PickListUploadEntity> listEntity3 = new ObservableField<>(new PickListUploadEntity());
    public ObservableField<PickListUploadEntity> listEntity4 = new ObservableField<>(new PickListUploadEntity());
    public ObservableField<PickListUploadEntity> listEntity5 = new ObservableField<>(new PickListUploadEntity());
    public ObservableField<String> areaCode = new ObservableField<>("");
    private PickRequireListFragment3 fragment3;
    private PickRepertory repertory;
    private int page = 1;
    private int size = 10;
    public int total;

    public PickRequireListFragModel3(PickRequireListFragment3 fragment3, PickRepertory repertory) {
        this.fragment3 = fragment3;
        this.repertory = repertory;
        areaCode.set(repertory.getAreaCode());
    }

    public String getAreaNameModel() {
        return repertory.getAreaName();
    }

    public String getAreaCodeModel() {
        return repertory.getAreaCode();
    }

    //工程招采列表
    public void getList1(boolean isLoadMore, String areaCode) {
        page = isLoadMore ? page + 1 : 1;
        listEntity1.get().setAreaCode(areaCode);
        listEntity1.get().setPageNum(page);
        listEntity1.get().setPageSize(size);
        APIManager.getInstance().getPickAPI().getProjectList(listEntity1.get()).enqueue(new Callback<BaseEntity<ProListEntity<List<ProjectBuyEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<ProjectBuyEntity>>>> call, Response<BaseEntity<ProListEntity<List<ProjectBuyEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                fragment3.showTop(isLoadMore);
                fragment3.showList1(response.body().getData().getList(), isLoadMore);
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<ProjectBuyEntity>>>> call, Throwable t) {
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    //材料列表
    public void getList2(boolean isLoadMore, String areaCode) {
        page = isLoadMore ? page + 1 : 1;
        listEntity2.get().setPageNum(page);
        listEntity2.get().setPageSize(size);
        listEntity2.get().setAreaCode(areaCode);
        APIManager.getInstance().getPickAPI().getMaterialClassList(listEntity2.get()).enqueue(new Callback<BaseEntity<ProListEntity<List<PickMaterialClassEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<PickMaterialClassEntity>>>> call, Response<BaseEntity<ProListEntity<List<PickMaterialClassEntity>>>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment3.showTop(isLoadMore);
                    fragment3.showList2(response.body().getData().getList(), isLoadMore);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<PickMaterialClassEntity>>>> call, Throwable t) {
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    //租赁列表
    public void getList3(boolean isLoadMore, String areaCode) {
        page = isLoadMore ? page + 1 : 1;
        repertory.getPickDeviceList(page, size, areaCode, listEntity3.get().getCityNo())
                .subscribe(new Consumer<BaseEntity<ListResponse<List<PickDeviceEntity2>>>>() {
                    @Override
                    public void accept(BaseEntity<ListResponse<List<PickDeviceEntity2>>> listResponseBaseEntity) throws Exception {
                        if (listResponseBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            fragment3.showTop(isLoadMore);
                            fragment3.showList3(listResponseBaseEntity.getData().getList(), isLoadMore);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }

    //劳务列表
    public void getList4(boolean isLoadMore, String areaCode) {
        page = isLoadMore ? page + 1 : 1;
        repertory.getPickLaborList(page, size, areaCode, listEntity4.get().getCityNo())
                .subscribe(new Consumer<BaseEntity<ListResponse<List<PickLabourEntity>>>>() {
                    @Override
                    public void accept(BaseEntity<ListResponse<List<PickLabourEntity>>> listResponseBaseEntity) throws Exception {
                        if (listResponseBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            fragment3.showTop(isLoadMore);
                            fragment3.showList4(listResponseBaseEntity.getData().getList(), isLoadMore);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }

    //工程施工列表
    public void getList5(boolean isLoadMore, String areaCode) {
        page = isLoadMore ? page + 1 : 1;
        repertory.getPickPackersList(page, size, areaCode, listEntity5.get().getCityNo(), null, listEntity5.get().getType())
                .subscribe(new Consumer<BaseEntity<ListResponse<List<PickPackersEntity>>>>() {
                    @Override
                    public void accept(BaseEntity<ListResponse<List<PickPackersEntity>>> listResponseBaseEntity) throws Exception {
                        if (listResponseBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            fragment3.showTop(isLoadMore);
                            fragment3.showList5(listResponseBaseEntity.getData().getList(), isLoadMore);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }

    //工程类型筛选
    public void getFilterEngineeringType() {
        repertory.getPickEngineeringType()
                .subscribe(new Consumer<BaseEntity<List<DictEntity3>>>() {
                    @Override
                    public void accept(BaseEntity<List<DictEntity3>> listBaseEntity) throws Exception {
                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            fragment3.showEngineeringPopWindow(listBaseEntity.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }

    //材料类型筛选
    public void getFilterMaterialType() {
        repertory.getPickMaterialType()
                .subscribe(new Consumer<BaseEntity<List<DictEntity3>>>() {
                    @Override
                    public void accept(BaseEntity<List<DictEntity3>> listBaseEntity) throws Exception {
                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            fragment3.showTypePopWindow(listBaseEntity.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }

    //项目规模筛选
    public void getFilterScale() {
        repertory.getPickScale("1")  //0：招采规模配置，1：项目规模配置，2：价格配置
                .subscribe(new Consumer<BaseEntity<List<DictEntity3>>>() {
                    @Override
                    public void accept(BaseEntity<List<DictEntity3>> listBaseEntity) throws Exception {
                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            fragment3.showScalePopWindow(listBaseEntity.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }

    //地区筛选
   /* public void getFilterAreaModel() {
        repertory.getAreaSecond2(areaCode.get())
                .subscribe(new Consumer<BaseEntity<List<DictEntity3>>>() {
                    @Override
                    public void accept(BaseEntity<List<DictEntity3>> listBaseEntity) throws Exception {
                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            fragment3.showAreaPopWindow(listBaseEntity.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }*/

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog2(fragment3.getActivity(), null, "登录中", 0, false, null,false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(fragment3.getActivity(), SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        fragment3.getActivity().startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                DialogHelper.dismissProgressDialog();
                SharedPreferenceUtil.getInstance().cleatData();
                saveUserInfo(response.body().getData());
                MToast.showToast(fragment3.getActivity(), "登录成功");
                fragment3.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                JPushInterface.setAlias(fragment3.getActivity(), 1, response.body().getData().getPhone());
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog2(fragment3.getActivity(), null, "请求中...", 0, false, null,false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    fragment3.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(fragment3.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getProvinceData() {
        Map map = new HashMap();
        map.put("areaCode", repertory.getAreaCode());
        DialogHelper.showProgressDialog2(fragment3.getContext(), null, "数据加载中...", 0, false, null,false);
        APIManager.getInstance().getPickAPI().getLocationNew(map).enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment3.setProvinceDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getCityData(String province) {
        DialogHelper.showProgressDialog2(fragment3.getContext(), null, "数据加载中...", 0, false, null,false);
        APIManager.getInstance().getPickAPI().getAreaSecond(province).enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment3.setCityDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }

}
